﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
#if UNITY_EDITOR
using UnityEditor;
#endif
public partial class HairGen
{
    public Hair LoadHairToCurrent(HairData hd)
    {
        return LoadHairTo(hd, hairCurr);
    }
    public Hair LoadHairTo(HairData hd, Hair hair)
    {
        var name = hair.gameObject.name;
        var pair = hair.curveData.pair;
        var curve = hair.curveData.curve;
        var length = hair.genData.length;

        DeleteHair(hair);


        Transform rig; Hair h;
        NewRigGO(name, out h, out rig); /////

        h.genData = hd.genData;
        h.genData.mono = h;
        h.genData.length = length;

        h.curveData = hd.curveData;
        h.curveData.mono = h;
        h.curveData.curve = curve;

        GenMeshTool.GenHair(h, hairMat, rig);

        Hair pairNew = null;

        if (pair != null)
        {
            pairNew = h.Copy();
            pairNew.name = pair.name;
            if (pair != null) DeleteHair(pair);
            h.curveData.pair = pairNew;
        }

        h.curveData.SnapBonesToCurve();

        if (pairNew != null)
        {
            hairs.Add(h.curveData.pair);
        }
        hairs.Add(h);
        Selector.current = h.transform;
        OnClickHair();
        return h;
    }
    public Hair LoadHairFromData(HairData hd)
    {
        Transform rig; Hair h;
        NewRigGO(hd.name, out h, out rig);

        h.renderData = hd.renderData;

        h.genData = hd.genData;
        h.genData.mono = h;

        if (overrideBonePerLength)
        {
            h.genData.bonesCount = Mathf.RoundToInt(h.genData.length * bonePerLength);
            h.genData.bonesCount = Mathf.Max(boneCountMin, h.genData.bonesCount);
        }

        h.curveData = hd.curveData;
        h.curveData.mono = h;

        GenMeshTool.GenHair(h, hairMat, rig);
        h.curveData.SnapBonesToCurve();

        hairs.Add(h);
        Selector.current = h.transform;
        return h;
    }
    public Hair GetMasterHair(Hair hair)
    {
        foreach (var h in I.hairs)
        {
            var hs = h.curveData.relaHairs;
            if (hs != null && hs.Contains(hair))
                return h;
        }
        return hair;
    }
    public bool onlySelectCircleMaster = true;
    Transform OnClick(Transform target)
    {
        // 选中rl头发时会变为选中主头发
        if (!onlySelectCircleMaster) return target;
        else return GetMasterHair(target.GetComponent<Hair>()).transform;
    }
    void SetDataFromHair(Hair h)
    {
        var info = h.genData;

        _length = length = info.length;

        curveBoneLength = info.curveBoneLength;

        _hairWidth = hairWidth = info.width;
        curveWidth = info.curveWidth;

        _hairThickness = hairThickness = info.thickness;
        curveThickness = info.curveThickness;

        curveCrsSecFront = info.curveCrsSecFront;
        curveCrsSecBack = info.curveCrsSecBack;
    }
    GenData GetDataFromInspector(Hair h, float length, bool useFactor = true)
    {
        GenData info = new GenData(h);
        info.length = length;
        info.vertsInY = Math.Max(10, Mathf.RoundToInt(length * vertsPerLength)); //根据长度和系数决定顶点和骨骼数
        info.bonesCount = Math.Max(2, Mathf.RoundToInt(length * bonePerLength));
        info.curveBoneLength = curveBoneLength.Clone();

        info.width = hairWidth;
        if (useFactor) info.width += info.length * lengthToWidthAddFactor; // 越长越宽
        info.curveWidth = curveWidth.Clone();

        info.thickness = hairThickness;
        if (useFactor) info.thickness += info.length * lengthToThicknessAddFactor;
        info.curveThickness = curveThickness.Clone();

        info.curveCrsSecFront = curveCrsSecFront;
        info.curveCrsSecBack = curveCrsSecBack;
        return info;
    }
    Hair AddHair(string name, float length)
    {
        Transform rig; Hair h;
        NewRigGO(name, out h, out rig);

        h.genData = GetDataFromInspector(h, length); ;

        h.curveData = new CurveData(h);
        GenMeshTool.GenHair(h, hairMat, rig);
        h.curveData.SnapBonesToCurve();

        hairs.Add(h);
        return h;
    }
    public string folderPathSave = @"Assets\HairMeshs";
    [ShowButton("保存到资源文件（默认覆盖）")]
    void SaveToAsset()
    {
        //string folderPath = EditorUtility.SaveFolderPanel("Hair Meshs folder", @"\Assets\HairMeshs", "");
        if (folderPathSave.GetDirOrCreate().Length > 0)
        {
            foreach (var hair in hairs)
            {
                var name = hair.gameObject.name;
                //name = name.Replace(" ", "_");
                var smr = hair.GetComponent<SkinnedMeshRenderer>();
                var path = folderPathSave + name + ".mesh";
                if (File.Exists(path)) AssetDatabase.DeleteAsset(path);
                AssetDatabase.CreateAsset(smr.sharedMesh, path);
            }
        }
    }
    [ShowButton("删除所有头发")]
    void ClearHairs()
    {
        this.Find().ClearChildren();
        hairs.Clear();
    }
    [ShowButton("烘焙蒙皮网格为普通网格（TODO）")]
    void BakeSmrs()
    {

    }
    [ShowButton("烘焙后根据姿态重新蒙皮（TODO）")]
    void ReSkin()
    {

    }
    GameObject NewRigGO(string name, out Hair h, out Transform rig)
    {
        var pool = this.Find();
        var go = new GameObject(name);
        go.SetParent(pool);
        h = go.AddComponent<Hair>();
        rig = new GameObject("Rig").transform;
        rig.SetParent(go);
        go.layer = layerHairNum;
        return go;
    }
}
